import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {TableUtil} from "../../../../util/table-util";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../../util/response-util";
import {MonitorService} from "../monitor.service";
import {PageSubject} from "../../../../util/page-subject";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {MsgResult} from "../../../../models/msg-result";
import {API, MsgConstants} from "../../../../constants/constants";
import {SitesService} from "../../sites/sites.service";
import {Monitor} from "../monitor";
import {isUndefined} from "util";

declare let $ ;

@Component({
  selector: 'app-monitor-assign-site',
  templateUrl: './monitor-assign-site.component.html',
  styleUrls: ['./monitor-assign-site.component.css']
})
export class MonitorAssignSiteComponent implements OnInit {

  table;

  notAssignSiteTable;

  //设备编号,保存时使用。
  snCode:string;
  //设备id,保存时使用。
  monitorId:string;
  //设备类型编码,保存时使用。
  monitorCode:string;

  siteTypeCode:string = 'a';

  siteCode:string ;
  //站点类型
  siteCategoryList;
  //设备对象
  monitor :Monitor;



  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private tableUtil: TableUtil,
    private dialogService: OneDialogService,
    private responseUtil:ResponseUtil,
    private monitorService : MonitorService,
    private sitesService : SitesService,
    private pageSubject: PageSubject
  ) {
    this.initMonitorObj();
  }

  ngOnInit() {
      this.initAssignedSite();
      this.loadNotAssignSite();
      this.initSiteCategory();
      this.pushPage();
  }

  /**
   *  生成面包屑
   */
  private pushPage() {
    let path = new Path("设备管理", null);
    this.pageSubject.pushPage("分配站点", "操作", path);
  }

  /**
   * 获取设备id
   */
  initAssignedSite(){
    let id = this.route.snapshot.params['id'];
    if(!!id){
        this.getSiteMonitorInfo(id);
    }else{
      this.dialogService.modalInfo('请选择一条信息！');
    }
  }

  /**
   *  根据设备id查询设备信息
   * @param id:设备id
   */
  private getSiteMonitorInfo(id){
      this.monitorService.getSiteMonitorById(id).subscribe(
        result => this.responseUtil.success(result, this.processSelectMonitorResult),
        message => this.responseUtil.error(message)
      )
  }

  /**
   * 处理查询的设备信息
   * @param {MsgResult} result
   */
  private processSelectMonitorResult =(result:MsgResult)=>{
    if(result && result.code == MsgConstants.MSG_CODE_OK){
      this.snCode = result.data.snCode;
      this.monitorId = result.data.id;
      // 根据设备类型，站点编码查询站点信息
      this.monitorCode = result.data.monitorCode;
      this.siteCode = result.data.siteCode;
      // 加载已分配站点数据
      this.loadSite();
    }
    if(result && result.code != MsgConstants.MSG_CODE_OK){

    }
  }

  /**
   * 查询已分配站点数据
   */
  loadSite(){
    this.table = this.tableUtil.load("one_table_ownDevice",{
      columns:[
        { field: "id", title:'ID',align:'left',visible:false,switchable:false},
        { field: "siteCode", title:'站点编码',align:'left',visible:false,switchable:false},
        { field: "siteName", title:'站点名称',align:'left'},
        { field: "siteTypeName", title:'站点类型',align:'left'},
        { field: "snCode" ,title:'设备编码',align:'left'},
        { field: "monitorId" ,title:'设备id',align:'left',visible:false},
        { field: "monitorCode" ,title:'设备类型编码',align:'left',visible:false},
        { field: "regionName",title:'行政区划' ,align:'left'},
        { field: "address",title:'站点位置' ,align:'left'},
        { field: "isThied",title:'第三方' ,align:'left',width:'80',formatter : this.yesOrNoFormat},
        { field: "isMove",title:'移动设备' ,align:'left',width:'80',formatter : this.yesOrNoFormat},
        { field: "isUse",title:'启用' ,align:'left',width:'80',formatter : this.yesOrNoFormat},
        { field: "createDate",title:'创建时间' ,align:'left' ,sortName:"CREATEDATE",sortable:true,visible: false},
        { field: 'operate', title: '操作', align: 'center', width:'50', events: this.operateEvents,  formatter: this.operateFormatter}
      ],
      idField:"id",
      sidePagination:'server',
      pagination:true,
      pageNumber:1,
      pageSize:5,
      pageList: [10,15, 50],
      paginationPreText:"上一页",
      paginationNextText:"下一页",
      paginationLoop:false,//是否开启循环分页
      singleSelect: true,//多选
      clickToSelect:true,//点击选中
      toolbar:".one-operation",
      url:API.sitePageListV2,
      method:'post',
      //传递附加参数
      queryParams:(params) => {
        params.siteCode = isUndefined(this.siteCode)?'a':this.siteCode;
        params.monitorCode = this.monitorCode;
        return params;
      },
      //返回数据处理器
      responseHandler:(result)=>{
        return this.responseUtil.bsPageHandler(result,(result)=>{
          result.data.rows.forEach(function (value) {
            value.createDate = value.createDate || '';
          });
        });
      },
      height:300,//table高度
      sortable:true,
      order:'asc',
      sortName:'CREATEDATE',
      showColumns:false,//显示自定义显示列按钮
      showRefresh:false,//显示刷新按钮
      minimumCountColumns:3,//最少保留显示的列数量
      showToggle:false,//显示视图切换按钮
      showPaginationSwitch:false,//显示是否分页切换按钮
      showExport: false,       //是否显示导出按钮
      exportDataType: 'all', //导出类型
      buttonsAlign: "right",  //按钮位置
      exportTypes: ['excel'],  //导出文件类型
      exportOptions: {
        ignoreColumn: [0],  //根据索引忽[0,1,2]略某一列的导出数据
        fileName: '站点数据报表',  //保存文件名称设置
        worksheetName: 'sheet1',  //表格工作区名称
        tableName: '设备数据报表',
        excelstyles: ['background-color', 'color', 'font-size', 'font-weight'],

      },
      classes:"table table-hover",
      striped:true,//隔行变色
      mobileResponsive:true//响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }

  /**
   * 添加删除操作标识
   * @param value
   * @param row
   * @param index
   * @returns {string}
   */
  private operateFormatter(value, row, index) {
    return [
      '<a class="remove" href="javascript:void(0)" title="Remove">',
      '<i class="glyphicon glyphicon-remove"></i>',
      '</a>'
    ].join('');
  }

  /**
   *  获取删除行的数据
   * @type {{[click .remove]: any}}
   */
  operateEvents = {
    'click .remove': function (e, value, row, index) {
      this.updateSiteMonitor(row.monitorId, row.snCode, row.monitorCode);
    }.bind(this)
  };


  /**
   * 修改站点已分配设备
   *  1.点击删除操作时，修改该设备的站点为空，状态为停用，
   *  2.同时，该设备会从已分配列表转化到未分配列表中
   * @param id
   * @param snCode
   * @param monitorCode
   */
  private updateSiteMonitor (monitorId, snCode, monitorCode){
    if (!monitorId) {
      this.dialogService.modalInfo("请选择一条信息！", this.search);
    }
    this.monitor.id = monitorId;
    this.monitor.siteCode = "";
    this.monitor.snCode = snCode;
    this.monitor.monitorCode = monitorCode;
    this.monitorService.siteMonitorEdit(this.monitor).subscribe(
      result => this.responseUtil.success(result, this.processEditMonitorResult),
      message => this.responseUtil.error(message)
    )
  }

  /**
   *  处理修改结果
   * @param result
   */
  private processEditMonitorResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.table.bootstrapTable('refresh');
      this.notAssignSiteTable.bootstrapTable('refresh');
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalInfo(result.message);
    }
  }

  /**
   * 初始化对象
   */
  private initMonitorObj(){
    this.monitor = new Monitor();
  }

  /**
   * 初始化站点类型
   */
  initSiteCategory(){
    this.sitesService.getSiteCategoryInfos().subscribe(
      result =>this.responseUtil.success(result ,this.processSiteCategoryResult),
      error => this.responseUtil.error(error)
    );
  }

  private processSiteCategoryResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.siteCategoryList = result.data;
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 搜索刷新
   */
  search(){
    this.siteTypeCode =$("#siteCategoryCode").val();
    this.notAssignSiteTable.bootstrapTable('refresh');
  }


  /**
   * 加载未分配站点
   */
  loadNotAssignSite(){
    this.notAssignSiteTable = this.tableUtil.load("one_table_monitor",{
      columns:[
        { checkbox: true },
        { field: "id", title:'ID',align:'left',visible:false,switchable:false},
        { field: "siteCode", title:'站点编码',align:'left',visible:false,switchable:false},
        { field: "siteName", title:'站点名称',align:'left'},
        { field: "siteTypeName", title:'站点类型',align:'left'},
        { field: "snCode" ,title:'设备编码',align:'left'},
        { field: "regionName",title:'行政区划' ,align:'left'},
        { field: "address",title:'站点位置' ,align:'left'},
        { field: "isThied",title:'第三方' ,align:'left',width:'80',formatter : this.yesOrNoFormat},
        { field: "isMove",title:'移动设备' ,align:'left',width:'80',formatter : this.yesOrNoFormat},
        { field: "isUse",title:'启用' ,align:'left',width:'80',formatter : this.yesOrNoFormat},
        { field: "createDate",title:'创建时间' ,align:'left' ,sortName:"CREATEDATE",sortable:true},
        { field: "updateDate",title:'修改时间' ,align:'left' ,sortName:"UPDATEDATE",sortable:true}
      ],
      idField:"id",
      sidePagination:'server',
      pagination:true,
      pageNumber:1,
      pageSize:10,
      pageList: [10,15, 50],
      paginationPreText:"上一页",
      paginationNextText:"下一页",
      paginationLoop:false,//是否开启循环分页
      singleSelect: true,//多选
      clickToSelect:true,//点击选中
      toolbar:".one-operation",
      url:API.sitePageListV2,
      method:'post',

      //传递附加参数
      queryParams:(params) => {
        params.siteName = $("#siteName").val();
        params.siteTypeCode = isUndefined(this.siteTypeCode)? '':this.siteTypeCode;
        params.snCode = $("#snCode").val();
        params.regionName = $("#regionName").val();
        params.editor = $("input[name='isSiteName']:checked").val();
        return params;
      },
      //返回数据处理器
      responseHandler:(result)=>{
        return this.responseUtil.bsPageHandler(result,(result)=>{
          result.data.rows.forEach(function (value) {
            value.createDate = value.createDate || '';
          });
        });
      },
      height:400,//table高度
      sortable:true,
      order:'ASC',
      sortName:'CREATEDATE',
      showColumns:false,//显示自定义显示列按钮
      showRefresh:false,//显示刷新按钮
      minimumCountColumns:3,//最少保留显示的列数量
      showToggle:false,//显示视图切换按钮
      showPaginationSwitch:false,//显示是否分页切换按钮
      showExport: false,       //是否显示导出按钮
      exportDataType: 'all', //导出类型
      buttonsAlign: "right",  //按钮位置
      exportTypes: ['excel'],  //导出文件类型
      exportOptions: {
        ignoreColumn: [0],  //根据索引忽[0,1,2]略某一列的导出数据
        fileName: '站点数据报表',  //保存文件名称设置
        worksheetName: 'sheet1',  //表格工作区名称
        tableName: '设备数据报表',
        excelstyles: ['background-color', 'color', 'font-size', 'font-weight'],

      },
      classes:"table table-hover",
      striped:true,//隔行变色
      mobileResponsive:true//响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat(value,row,index){
    if(value == '0'){
      return "否";
    }
    if(value == '1'){
      return "是";
    }
  }


  /**
   *  保存选中的站点信息时，验证信息是否存在
   *  1.判断设备类型，设备编码，设备id是否存在。
   */
  saveAssignSite(){
    if(!this.monitorCode){
      return this.dialogService.modalInfo("该设备的设备类型为空！");
    }
    if(!this.snCode){
      return this.dialogService.modalInfo("该设备的设备编号不存在！");
    }
    if(!!this.monitorId){
      this.isAssignSite(this.monitorId);
    }else{
      return this.dialogService.modalInfo("设备不存在！");
    }
  }

  /**
   * 保存分配的设备
   * @param monitorId：设备id
   * @returns {any}
   */
  isAssignSite(monitorId) {
    let rows = this.notAssignSiteTable.bootstrapTable('getSelections');
    if (!rows[0]) {
      return this.dialogService.modalWarn("请选择一条消息！");
    }
    //站点编码
    this.siteCode = this.tableUtil.getCloumn(rows[0], "siteCode");

    let params = "siteCode=" + this.siteCode + "&snCode=" + this.snCode + "&monitorCode=" + this.monitorCode;
    if (!!params && !!monitorId) {
      this.monitorService.assignSite(params, monitorId).subscribe(
        result => this.responseUtil.success(result, this.processSiteMonitorResult),
        message => this.responseUtil.error(message)
      );
    }
  }

  /**
   * 处理分配设备的结果
   * @param result
   */
  private processSiteMonitorResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      //更新未分配站点bootstrap table数据
      this.notAssignSiteTable.bootstrapTable('refresh');
      //更新已分配站点bootstrap table数据
      this.table.bootstrapTable('refresh');
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 取消分配
   */
  cancelAssignSite() {
      this.router.navigate(['..'], {relativeTo: this.route});
  }


}
